from fastapi.params import Depends
from pydantic.errors import SequenceError
from database import SessionLocal, Base, engin
from fastapi import APIRouter, HTTPException
from sqlalchemy.orm import Session
from . import schemas, crud
from starlette import status
from fastapi.security import OAuth2PasswordRequestForm
from common import jwt_utils


userApi = APIRouter()

Base.metadata.create_all(bind=engin)


def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


# 创建用户
@userApi.post("/create_user", response_model=schemas.ReadUser, summary="创建用户")
async def create_user(user: schemas.CreateUser, db: Session = Depends(get_db)):
    db_user = crud.get_user_name(db=db, username=user.username)
    print(db_user is None)
    if db_user:
        raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="用户已存在")
    return crud.create_user(db=db, user=user)


# 根据用户id查询用户信息
@userApi.get("/get_user/{userID}", response_model=schemas.ReadUser, summary="根据用户id查询用户信息")
async def get_user(userID: int, db: Session = Depends(get_db)):
    user_data = crud.get_user(db=db, user_id=userID)
    if user_data is None:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
    return user_data


# 查询用户列表
@userApi.get("/get_users", summary="查询用户列表")
async def get_users(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
    data = crud.get_users(db=db, skip=skip, limit=limit)
    return data


# 用户登录
@userApi.post("/login_user", response_model=schemas.Token, summary="用户登录")
async def login_user(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    username = form_data.username
    password = form_data.password
    access_token = crud.user_login(db=db, username=username, password=password)
    return {"access_token": access_token, "token_type": "bearer"}

# jwt解析
@userApi.post("/decode_jwt", summary="jwt解析")
async def decode_jwt(current_user: schemas.ReadUser = Depends(jwt_utils.jwt_get_current_active_user)):
    return current_user
